package cn.zvo.websocket.framework.springboot.util;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import cn.zvo.log.framework.springboot.LogUtil;
import cn.zvo.log.vo.LogListVO;
import cn.zvo.websocket.framework.springboot.vo.MessageListVO;
import cn.zvo.websocket.framework.springboot.vo.MessageReceiveVO;
import net.sf.json.JSONObject;

/**
 * 消息存储相关
 * @author 管雷鸣
 */
@Component(value="KefuCoreMessageStorageUtil")
public class MessageStorageUtil{
	public static String logstore = "message";	//专门存储message聊天记录的日志库名字
	
	/**
	 * 推送一条消息进行存储
	 * @param msg socket 接收到的消息，当socket接收到消息后，会立即推送过来
	 */
	public static void push(MessageReceiveVO msg){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("type", msg.getType());
		map.put("receiveId", msg.getReceiveId());
		map.put("sendId", msg.getSendId());
		map.put("text", msg.getText());
		map.put("time", msg.getTime());
		
		LogUtil.add(map);
	}
	
	
	/**
	 * 查看我跟某人的历史聊天记录
	 * @param myChatid 当前我的chatid
	 * @param otherChatId 跟我聊天对方的chatid
	 * @param time 13位时间戳，要获取这个时间之前的记录
	 * @param number 要获取多少条记录，取值10~200之间，不传默认是100条
	 * @param type 类型，取数据的类型，可传入 before、after，  before:向前，也就是取<time的记录，after:向后,也就是取>time的记录 。默认不传则是before
	 */
	public static MessageListVO chatLog(String myChatid, String otherChatId, long time, int number, String type, HttpServletRequest request){
		MessageListVO vo = new MessageListVO();
		
		//组合查询条件
		String query = "((sendId="+myChatid+" AND receiveId="+otherChatId+") OR (sendId="+otherChatId+" AND receiveId="+myChatid+")) ";
		//这是 aliyun sls 的，es不知行不行
		if(type.equalsIgnoreCase("before")){
			query = query + "AND time < "+time;
		}else if(type.equalsIgnoreCase("after")){
			query = query + "AND time > "+time;
		}
		
		//每页多少条-参数校验
		if(number < 10){
			number = 10;
		}
		if(number > 200){
			number = 200;
		}
		
		//type-参数校验
		if(!(type.equalsIgnoreCase("before") || type.equalsIgnoreCase("after"))){
			vo.setBaseVO(MessageListVO.FAILURE, "type传入错误！请传入after、before");
			return vo;
		}
		
		
		LogListVO logListVO = LogUtil.list(query, number, 1);
		BeanUtils.copyProperties(logListVO, vo);
		
		vo.setEndTime(time);
		if(vo.getJsonArray().size() > 0){
			//如果有数据，那么取最后一条的时间
			JSONObject lastJson = vo.getJsonArray().getJSONObject(vo.getJsonArray().size() -1);
			vo.setStartTime(getLong(lastJson, "time"));
		}
		
		return vo;
	}
	
	/**
	 * 取json的long类型value
	 */
	private static long getLong(JSONObject json, String key){
		if(json.get(key) != null){
			return json.getLong(key);
		}
		return 0;
	}
}
